package com.mxgraph.swing.handler;

import com.mxgraph.view.mxEdgeStyle;
import com.mxgraph.view.mxCellState;
import com.mxgraph.util.mxPoint;
import com.mxgraph.model.mxCell;

import java.util.List;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 *
 * @author Wang Jiaxiang
 *         Date: 2011-2-21
 */
public class htEdgeStyleFunction implements mxEdgeStyle.mxEdgeStyleFunction {
    public void apply(mxCellState state, mxCellState source, mxCellState target, List<mxPoint> points, List<mxPoint> result) {
        if (points == null)
            return;

        mxCell cell = (mxCell) state.getCell();
        //if(!cell.getStyle().contains("htLine"))
        //    return;
        mxPoint sourceClone = (mxPoint) cell.getGeometry().getSourcePoint().clone();
        mxPoint targetClone = (mxPoint) cell.getGeometry().getTargetPoint().clone();
        mxPoint sourcePoint = state.getView().transformControlPoint(state, cell.getGeometry().getSourcePoint());
        mxPoint targetPoint = state.getView().transformControlPoint(state, cell.getGeometry().getTargetPoint());
        state.getAbsolutePoints().set(0, sourcePoint);
        state.getAbsolutePoints().set(state.getAbsolutePointCount() -1, targetPoint);
        result.clear();
        result.add(state.getAbsolutePoint(0));
        List<mxPoint> temp = new ArrayList<mxPoint>();
        if (!points.contains(sourceClone)) {
            temp.add(sourcePoint);
        }
        temp.addAll(points);
        if (!temp.contains(targetClone))
            temp.add(targetPoint);
        points.clear();
        for (mxPoint p : temp)
            points.add(p);
        int pointCount = points.size();
        double scale = state.getView().getScale();
        for (int i = 0; i < pointCount; i++) {
            if (i == pointCount - 1)
                continue;
            if (i > 0)
                result.add(state.getView().transformControlPoint(state, points.get(i)));
            mxPoint p = trasformControPoint(state.getView().transformControlPoint(state, points.get(i)), state.getView().transformControlPoint(state, points.get(i+1)));
            result.add(p);
        }
    }

    private mxPoint trasformControPoint(mxPoint absolutePoint, mxPoint absolutePoint1) {
        return new mxPoint((absolutePoint.getX() + absolutePoint1.getX()) / 2.0,
                (absolutePoint.getY() + absolutePoint1.getY()) / 2.0);
    }
}
